package org.wutopia.leo.resource;



import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
//import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.wutopia.leo.applicaiton.payment.PaymentApplicationService;
import org.wutopia.leo.domain.account.Account;
import org.wutopia.leo.domain.auth.CurrentAccount;
import org.wutopia.leo.domain.payment.Payment;
import org.wutopia.leo.infrastructure.jaxrs.CodedMessage;
import org.wutopia.leo.infrastructure.jaxrs.CommonResponse;


/**
 * 支付单相关的资源
 *
 **/
@RequestMapping("/api/v1/pay")
@RestController
public class PaymentResource {

    @Autowired
    private PaymentApplicationService service;

    /**
     * 修改支付单据的状态
     */
    @PatchMapping("/{payId}")
    public ResponseEntity<CodedMessage> updatePaymentState(@PathVariable("payId") String payId, @RequestParam("state") Payment.State state, @CurrentAccount Account account) {
//        Account account = (Account) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        account.getId()
        return updatePaymentStateAlias(payId, account.getId(), state);
    }

    /**
     * 修改支付单状态的GET方法别名
     * 考虑到该动作要由二维码扫描来触发，只能进行GET请求，所以增加一个别名以便通过二维码调用
     * 这个方法原本应该作为银行支付接口的回调，不控制调用权限（谁付款都行），但都认为是购买用户付的款
     */

    @GetMapping("/modify/{payId}")
    public ResponseEntity<CodedMessage> updatePaymentStateAlias(@PathVariable("payId") String payId, @RequestParam("accountId") Integer accountId, @RequestParam("state") Payment.State state) {
        if (state == Payment.State.PAYED) {
            return CommonResponse.op(() -> service.accomplishPayment(accountId, payId));
        } else {
            return CommonResponse.op(() -> service.cancelPayment(payId));
        }
    }

}
